﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace UmlDesigner.Model
{
    internal class Storage
    {
        static int FileTag = 0x2E464455;

        internal static Storage Open(Stream s)
        {
            Storage storage = new Storage(s);
            storage.reader = new BinaryReader(storage.stream);
            int fileTag = storage.LoadInt();
            if (fileTag != FileTag)
            {
                throw new Exception("Unknown file format!");
            }
            storage.version = storage.LoadInt();
            return storage;
        }

        internal static Storage BeginSave(Stream s)
        {
            Storage storage = new Storage(s);
            storage.writer = new BinaryWriter(storage.stream);
            storage.SaveInt(FileTag);
            storage.SaveInt(storage.latestVersion);
            return storage;
        }

        internal void Close()
        {
            stream.Close();
        }

        internal void SaveInt(int i)
        {
            writer.Write(i);
        }

        internal void SaveString(string s)
        {
            if (s == null)
            {
                writer.Write(false);
            }
            else
            {
                writer.Write(true);
                writer.Write(s);
            }
        }

        internal int LoadInt()
        {
            return reader.ReadInt32();
        }

        internal string LoadString()
        {
            if (reader.ReadBoolean())
            {
                return reader.ReadString();
            }
            else
            {
                return null;
            }
        }


        internal void SaveBool(bool p)
        {
            writer.Write(p);
        }
        
        internal bool LoadBool()
        {
            return reader.ReadBoolean();
        }

        internal int version = 2;
        internal int latestVersion = 2;

        private Storage(Stream s)
        {
            stream = s;
        }

        private Stream stream;
        private BinaryReader reader;
        private BinaryWriter writer;

    }
}
